package com.yun2.bms.dao.impl;

import com.yun2.bms.dao.ILendDao;
import com.yun2.bms.model.Lend;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author: youli
 * qq: 27855162@qq.com
 * date: 2020/5/25
 */

public class LendDaoImpl extends BaseDaoImpl implements ILendDao {

    @Override
    public Integer getLendedNumberByUserId(int userId) {
        Integer number = 0;
        String sql = "select count(*) from lend where user_id = ?";
        Object[] params = new Object[]{userId};
        super.queryBySql(sql, params);
        try {
            while (rs.next()) {
                number = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return number;
        }
    }

    @Override
    public Integer getLendedNumberByBookId(int bookId) {
        Integer number = 0;
        String sql = "select count(*) from lend where book_id = ?";
        Object[] params = new Object[]{bookId};
        super.queryBySql(sql, params);
        try {
            while (rs.next()) {
                number = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return number;
        }
    }

    @Override
    public int add(int userId, int bookId) {
        String sql = "insert into lend(user_id,book_id,lend_date)values(?,?,?)";
        Object[] params = new Object[]{userId, bookId, new Date()};
        return super.updateBySql(sql, params);
    }

    @Override
    public boolean bookIsLendedByUserId(int bookId, int userId) {
        Integer number = 0;
        String sql = "select count(*) from lend where book_id = ? and user_id = ?";
        Object[] params = new Object[]{bookId, userId};
        super.queryBySql(sql, params);
        try {
            while (rs.next()) {
                number = rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return number > 0 ? true:false;
        }
    }

    @Override
    public List<Lend> getAllByUserId(int userId) {
        List<Lend> list = new ArrayList<>();
        String sql = "select * from lend where user_id = ?";
        Object[] params = new Object[]{userId};
        super.queryBySql(sql, params);
        try{
            while(rs.next()){
                Integer id = rs.getInt("id");
                Integer uId = rs.getInt("user_id");
                Integer bookId = rs.getInt("book_id");
                Date lendDate = rs.getDate("lend_date");
                Lend lend = new Lend(id,userId,bookId,lendDate);
                list.add(lend);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return list;
        }
    }
}
